import json

from pythonProject.RealmRaid.assets import *
from pythonProject.tools.adb_shell import click_methods
from pythonProject.tools.ocr import ocr


def already_number(word):
    contents = []
    if not word:
        return ""
    result = ocr(ocr_number(word))
    data = json.loads(result)
    print("识别结果:", data)
    for block in data['data']['block']:
        for line in block['line']:
            for word in line['word']:
                content = word['content']
                contents.append(content)
    return contents

def ticket_number(word):
    contents = already_number(word)
    first_content = contents[0]
    print(first_content)
    slash_index = first_content.find("/")
    if slash_index == -1:
        raise ValueError("No '/' found in the first content")

    # 提取 "/" 前的字符
    numerator_str = first_content[:slash_index]
    # 将提取出的字符转换为整数
    challenge_ticket = int(numerator_str)
    print("还剩", challenge_ticket)
    return challenge_ticket

def fight_number(word):
    contents = already_number(word)
    print(contents)
    already_fight =int(contents[1])
    print("还剩", already_fight)
    return already_fight

ticket_number(Challenge_Ticket_Number)
fight_number(Already_Fight_Number)


def fight():
    medals = [MEDALS_5, MEDALS_4, MEDALS_3, MEDALS_2, MEDALS_1, MEDALS_0]

    for medal in medals:
        try:
            medal_image = image(medal)
            if medal_image is not None:
                click_methods(medal_image)
                click_methods(image(ATTACK))
                click_methods(image(READY))
                click_methods(image(Fight_Over))
                return True
        except Exception as e:
            # 处理异常，例如记录日志
            print(f"Error occurred while processing image {medal}: {e}")

    # 如果所有奖牌图像都不存在，返回 False
    return False

def run():
    while ticket_number(Challenge_Ticket_Number)==0:

        if fight_number(Already_Fight_Number) == 3 or 6:
            if image(PRIZE) is not None:
                click_methods(image(PRIZE))
        elif fight_number(Already_Fight_Number) == 8:
            fight_out_four()
            if image(PRIZE) is not None:
                click_methods(image(PRIZE))
        fight()
    pass

def fight_out_four():
    medals = [MEDALS_5, MEDALS_4, MEDALS_3, MEDALS_2, MEDALS_1, MEDALS_0]

    for medal in medals:
        try:
            medal_image = image(medal)
            if medal_image is not None:
                click_methods(medal_image)
                for _ in range(4):
                    click_methods(image(BACK))
                    click_methods(image(Fight_Again))
                click_methods(image(READY))
                click_methods(image(Fight_Over))
                return True
        except Exception as e:
            # 处理异常，例如记录日志
            print(f"Error occurred while processing image {medal}: {e}")
    # 如果所有奖牌图像都不存在，返回 False
    return False





